package com.woniu.sso_jwt.jwtcontroller;

import com.woniu.sso_jwt.jwtresponsedata.JWTResponseData;
import com.woniu.sso_jwt.jwtresult.JWTResult;
import com.woniu.sso_jwt.jwtsubject.JWTSubject;
import com.woniu.sso_jwt.jwtuser.JWTUsers;
import com.woniu.sso_jwt.jwtutils.JWTUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Controller
public class JWTConroller {
    //验证是否登录
    @RequestMapping("/testAll")
    @ResponseBody
    public Object testAll(HttpServletRequest request){
        String token=request.getHeader("Authorization");
        JWTResult result=JWTUtil.validateJWT(token);

        JWTResponseData responseData=new JWTResponseData();

        if(result.isSuccess()){
            responseData.setCode(200);
            responseData.setData(result.getClaims().getSubject());
            responseData.setMsg("验证成功，可以操作");
            //重新生成token，就是为了重置token的有效期
            String newToken=JWTUtil.createJWTToken(result.getClaims().getId(),
                    result.getClaims().getIssuer(),result.getClaims().getSubject(),60*1000);
            responseData.setToken(newToken);
            return responseData;
        }else{
            if(result.getErrCode()==1005){
                responseData.setCode(500);
                responseData.setMsg("登录超时，请重新登录");
            }else if(result.getErrCode()==1006){
                responseData.setCode(500);
                responseData.setMsg("验证失败");
            }

            return responseData;
        }
    }

    @RequestMapping("login")
    @ResponseBody
    public Object login(String username,String password){

        JWTResponseData responseData=null;
        //认证用户信息，数据库
        if(JWTUsers.isLogin(username,password)){
            JWTSubject subject=new JWTSubject(username);
            String jwtToekn = JWTUtil.createJWTToken(UUID.randomUUID().toString(),"sxt-test-jwt",
                    JWTUtil.generalSubject(subject),60*1000);
            responseData=new JWTResponseData();
            responseData.setCode(200);
            responseData.setData(null);
            responseData.setMsg("登录成功");
            responseData.setToken(jwtToekn);
        }else{
            responseData=new JWTResponseData();
            responseData.setCode(500);
            responseData.setData(null);
            responseData.setMsg("登录失败");
            responseData.setToken(null);
        }

        return responseData;
    }
    @RequestMapping("/")
public String toLogin(){
        return "index";
}
}
